<?php

namespace app\admin\controller;

use app\common\controller\Send;
use app\admin\model\Config AS ConfigModel;
use app\admin\validate\Config AS ConfigValidate;
use think\facade\Request;

class Config extends Base
{
    use Send;

    /**
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function form()
    {
        if (Request::instance()->isPost()) {
            $data = input('post.');

            // 检测变量
            $validate = new ConfigValidate();
            if (!$validate->check($data)) {
                return json(self::sendResult(102, [], $validate->getError()));
            }

            // 修改配置
            ConfigModel::saveData($data);

            return json(self::sendResult(self::$okCode, [
                'url' => url('form'),
            ]));
        } else {
            $shareText = ConfigModel::getOne('share_text');
            $commission = ConfigModel::getOne('commission');
            $agent_commission = ConfigModel::getOne('agent_commission');
            $sales_commission = ConfigModel::getOne('sales_commission');
            $switch = ConfigModel::getOne('switch');
            return view('form', [
                'shareText' => $shareText,
                'switch' => $switch,
                'commission' => $commission,
                'agent_commission' => $agent_commission,
                'sales_commission' => $sales_commission,
            ]);
        }
    }
}
